<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="goodsName" />
      <el-table-column label="所属仓库" align="center" prop="warehouseId">
        <template slot-scope="scope">
          {{ mapWarehouseName(scope.row.warehouseId) }}
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="goodsPrice" />
      <el-table-column label="数量" align="center" prop="goodsQuantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="商品信息" align="center" prop="info" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="handleQuantity(scope.row,'raise')"
            v-hasPermi="['system:goods:update']"
          >入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-remove-outline"
            @click="handleQuantity(scope.row,'reduce')"
            v-hasPermi="['system:goods:update']"
          >出库</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改goods对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择仓库">
            <el-option
              v-for="item in warehouses"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>        
        <el-form-item label="单价" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="数量" prop="goodsQuantity" v-if="form.goodsNum == null">
          <el-input v-model="form.goodsQuantity" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="商品信息" prop="info">
          <el-input v-model="form.info" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

        <!-- 出入库对话框 -->
    <el-dialog :title="title" :visible.sync="openQuantityForm" width="500px" append-to-body>
      <el-form ref="form" :model="editQuantityForm" :rules="editQuantityRules" label-width="80px">
        <el-form-item label="名称" prop="goodsName">
          <el-input v-model="editQuantityForm.goodsName" placeholder="请输入" disabled/>
        </el-form-item>
        <el-form-item label="数量" prop="editNum">
          <el-input v-model="editQuantityForm.editNum" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editQuantity">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/system/goods";
import { listWarehouse } from "@/api/system/warehouse"

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // goods表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
      },
      // 表单参数
      form: {},
      editQuantityForm:{},
      warehouses:[],
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" }
        ],
        goodsPrice: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        goodsQuantity: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        info: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      },
      editQuantityRules: {
        editNum: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      },
      openQuantityForm: false,
    };
  },
  created() {
    this.getList();
    this.getWarehouses(); // 加载仓库列表
  },
  computed: {
    mapWarehouseName(){
      return (id)=>{
        if(!this.warehouses.length) return ''
        return this.warehouses.find(item=>item.warehouseId == id)?.warehouseName || '未分配'
      }
    }
  },
  methods: {

    getWarehouses() {
      listWarehouse().then(response => {
        this.warehouses = response.rows;
      });
    },
    /** 查询goods列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsNum: null,
        goodsName: null,
        goodsPrice: null,
        goodsQuantity: null,
        unit: null,
        info: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsNum)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加goods";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsNum = row.goodsNum || this.ids
      getGoods(goodsNum).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改goods";
      });
    },
    /** 出入库操作 */
    handleQuantity(row,action) {
      this.title = action == "raise" ? '入库' : '出库';
      const goodsNum = row.goodsNum || this.ids
      getGoods(goodsNum).then(response => {
        let {goodsName,goodsQuantity} = response.data;
        console.log(goodsName,goodsQuantity);
        
        this.editQuantityForm.goodsNum = goodsNum
        this.editQuantityForm.goodsName = goodsName
        this.editQuantityForm.goodsQuantity = goodsQuantity
        // this.editQuantityForm.editNum = null
        this.openQuantityForm = true
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsNum != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    editQuantity(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          let { editNum } = this.editQuantityForm
          this.title == '入库' ? (this.editQuantityForm.goodsQuantity += parseInt(editNum)) : (this.editQuantityForm.goodsQuantity -= parseInt(editNum))
          
          updateGoods(this.editQuantityForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.openQuantityForm = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsNums = row.goodsNum || this.ids;
      let tips = row.goodsName ? `是否确认删除商品${row.goodsName}` : '是否确认删除选中商品'
      this.$modal.confirm(tips).then(function() {
        return delGoods(goodsNums);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
